<template>
  <div class="singer" ref='singer'>
    <list-view :dataList='singerList' @select='selectSinger' ref='listView'></list-view>
      <router-view></router-view>
  </div>
</template>

<script>
  import { artists } from 'api'
  import Singer from 'common/js/singer'
  import ListView from 'base/listView/listView'
  import { mapMutations } from 'vuex'
  import { playlistMixin } from 'common/js/mixin'

  const pinyin = require('pinyin')
  const HOT_NAME = '热门'

  export default {
    mixins: [playlistMixin],
    data() {
      return {
        singerList: []
      }
    },
    created() {
      this._getArtists()
    },
    methods: {
      handlePlaylist(newVal) {
        const bottom = newVal.length>0?'60px':'0'
        this.$refs.singer.style.bottom = bottom
        this.$refs.listView.refresh()
      },
      selectSinger(singer) {
        this.$router.push({
          path: `/singer/${singer.id}`
        })
        this.setSinger(singer)
      },
      _normalizeSinger(list) {
        let map = {
          hot: {
            title: HOT_NAME,
            item: []
          }
        }
        list.forEach((item, index) => {
          const py = pinyin(item.name, {
            style: pinyin.STYLE_FIRST_LETTER
          })[0][0][0].toUpperCase()
          if (index < 10) {
            map.hot.item.push(new Singer(item.id, item.name, item.img1v1Url))
          }

          if (!map[py]) {
            map[py] = {
              title: py,
              item: []
            }
          }
          map[py].item.push(new Singer(item.id, item.name, item.img1v1Url))
        })

        let hot = []
        let ret = []
        for (let key in map) {
          if (map[key].title.match(/[a-zA-Z]/)) {
            ret.push(map[key])
          } else {
            hot.push(map[key])
          }
        }
        ret.sort((a, b) => {
          return a.title.charCodeAt(0) - b.title.charCodeAt(0)
        })

        this.singerList = hot.concat(ret)
      },
      _getArtists() {
        artists().then((res) => {
          this._normalizeSinger(res.data.artists)
        })
      },
      ...mapMutations({
        setSinger: 'SET_SINGER'
      })
    },
    components: {
      ListView
    }
  }
</script>

<style lang="stylus" scoped>

  .singer
    position: fixed
    width: 100%
    top: 88px
    bottom: 0
</style>
